package exporter;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Hashtable;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import main.tokens;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

public class XmlFilePrinter 
{
	private ArrayList<String> arlHashTableKey;
	private Hashtable<String, ArrayList<tokens>> htAlphaTokens;

	public XmlFilePrinter(ArrayList<String> pHashTableKey,
			Hashtable<String, ArrayList<tokens>> pAlphaTokens) 
	{
		arlHashTableKey = pHashTableKey;
		htAlphaTokens = pAlphaTokens;
	}

	public void PrintResultIntoXML(String pLocation) 
	{
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder dbuilder = null;
		try 
		{
			dbuilder = dbf.newDocumentBuilder();
		} catch (Exception ex) 
		{
			ex.printStackTrace();
		}

		Document doc = dbuilder.newDocument();

		Element root = doc.createElement("Tokens");
		doc.appendChild(root);

		for (int i = 0; i < arlHashTableKey.size(); i++) 
		{
			if (!htAlphaTokens.get(arlHashTableKey.get(i)).get(0).getResult().equals(""))
			{
				Element elmCntToken = doc.createElement("Token");
				elmCntToken.setAttribute("Token", arlHashTableKey.get(i));
				root.appendChild(elmCntToken);

				String[] strsResult = htAlphaTokens.get(arlHashTableKey.get(i))
						.get(0).getResult().split(", ");
				for (int j = 0; j < strsResult.length; j++) 
				{
					Element elmResult = doc.createElement("Result");
					elmCntToken.appendChild(elmResult);
					Text elmResultText = doc.createTextNode(strsResult[j]);
					elmResult.appendChild(elmResultText);
				}
			}			
		}

		try 
		{
			File f = new File(pLocation);
			FileOutputStream fos = new FileOutputStream(f);
			StreamResult result = new StreamResult(fos);

			TransformerFactory transFactory = TransformerFactory.newInstance();
			Transformer transformer = transFactory.newTransformer();

			transformer.setOutputProperty("encoding", "UTF-8");
			transformer.setOutputProperty("indent", "yes");

			DOMSource source = new DOMSource(doc);

			transformer.transform(source, result);
			fos.close();
		} catch (Exception ex) 
		{
			ex.printStackTrace();
		}

	}
}
